package cn.ghx.xboot.brand;

import cn.ghx.xboot.attach.AttachmentService;
import cn.ghx.xboot.brand.dto.BrandCategoryDto;
import cn.ghx.xboot.dict.Dict;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.ghx.xboot.mapper.BrandMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ghx
 * @createDate 2024-03-04 22:10:05
 */
@Service
public class BrandService extends ServiceImpl<BrandMapper, Brand> {

    private final AttachmentService attachmentService;

    @Lazy
    public BrandService(AttachmentService attachmentService) {
        this.attachmentService = attachmentService;
    }

    public Page<Brand> query(String keyword,
                             Boolean hot,
                             String category,
                             Integer page, Integer size) {
        LambdaQueryChainWrapper<Brand> qw = lambdaQuery();
        if (StringUtils.hasText(keyword)) {
            qw.and(w -> {
                w.like(Brand::getName, keyword);
            });
        }
        if (hot != null) {
            qw.eq(Brand::getHot,hot);
        }
        if( StringUtils.hasText(category)){
            qw.eq(Brand::getCategory,category);
        }
        qw.orderByDesc(Brand::getCreateTime);
        Page<Brand> rs = qw.page(Page.of(page, size));
        rs.getRecords().forEach(this::wrapExtra);
        return rs;
    }

    public void wrapExtra(Brand i ){
        if (StringUtils.hasText(i.getLogo())) {
            i.setLogoAttach(attachmentService.getById(i.getLogo()));
        }
    }

    @Cacheable(cacheNames = "BrandService.getAll")
    public List<BrandCategoryDto> getAll() {
        List<BrandCategoryDto> rs = new ArrayList<>();
        List<Brand> list = list();
        list.forEach(this::wrapExtra);
        Map<String,List<Brand>> map = new HashMap<>();
        list.forEach(i -> {
            if (StringUtils.hasText(i.getCategory())) {
                List<Brand> brands = map.computeIfAbsent(i.getCategory(), k -> new ArrayList<>());
                brands.add(i);
            }
            if(i.getHot()){
                List<Brand> brands = map.computeIfAbsent("热门品牌", k -> new ArrayList<>());
                brands.add(i);
            }
        });

        for(String key: map.keySet()){
            BrandCategoryDto dto = new BrandCategoryDto();
            dto.setCategory(key);
            dto.setBrands(map.get(key));
            rs.add(dto);
        }

        return rs;
    }
}




